package com.example.prometheus.service;

import com.example.prometheus.model.Order;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class BeerService {
    private final MeterRegistry meterRegistry;

    private List<Order> orders = new ArrayList<>();

    public BeerService(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        /**
         # HELP beer_ordersInQueue Number of unserved orders
         # TYPE beer_ordersInQueue gauge
         beer_ordersInQueue{application="yt.prometheus",role="master",} 0.0
         */
        Gauge.builder("beer.ordersInQueue", orders, Collection::size)
                .description("Number of unserved orders")
                .register(meterRegistry);
    }

    /**
     * 对订单数据进行统计
     */
    public void orderBeer(Order order) {
        orders.add(order);
    }

    /**
     # HELP method_timed_seconds Time spent serving orders
     # TYPE method_timed_seconds summary
     method_timed_seconds_active_count{application="yt.prometheus",class="com.example.prometheus.service.BeerService",method="serveFirstOrder",role="master",} 0.0
     method_timed_seconds_duration_sum{application="yt.prometheus",class="com.example.prometheus.service.BeerService",method="serveFirstOrder",role="master",} 0.0
     # HELP method_timed_seconds_max Time spent serving orders
     # TYPE method_timed_seconds_max gauge
     method_timed_seconds_max{application="yt.prometheus",class="com.example.prometheus.service.BeerService",method="serveFirstOrder",role="master",} 0.0
     */
    @Scheduled(fixedRate = 5000)
    @Timed(description = "定时任务--数据操作耗时指标", longTask = true)
    public void serveFirstOrder() throws InterruptedException {
        if (!orders.isEmpty()) {
            Order order = orders.remove(0);
            Thread.sleep(1000L * order.getAmount());
        }
    }
}